package liming.tool.maven.info;

import liming.tool.json.ToJson;
import liming.tool.json.annotation.JsonMark;
import org.json.JSONObject;

import java.io.File;

@JsonMark("maven-java-config")
public class Project implements ToJson {
    @JsonMark
    public String javaHome;
    @JsonMark
    public String mavenHome;
    @JsonMark
    public String projectPath;
    @JsonMark
    public String mavenSettingPath;
    @JsonMark
    public Resources resources = new Resources();
    public Mode mainMode;

    @Override
    public void afterDeserialize(JSONObject json) {
        updateMode();
    }

    @Override
    public JSONObject serializeBody(Class<?> type) {
        JSONObject jsonBody = ToJson.super.serializeBody(type);
        if (mainMode != null)
            jsonBody.put("mainMode", mainMode.serialize());
        return jsonBody;
    }

    public void updateMode() {
        mainMode = new Mode() {
            @Override
            public String getModePath() {
                return getProjectPath();
            }

            @Override
            public Class<?> getDefaultClass() {
                return Mode.class;
            }
        };
        JSONObject mode = new JSONObject();
        mode.put("modePath", getProjectPath()).put("resources", resources.serializeBody(Resources.class));
        mainMode.deserialize(mode);
    }

    public String getPath(String modeName, String packageName, String className, String type) {
        return buildPath(mainMode.findModePath(modeName),packageName,className,type);
    }

    private String buildPath(String modePath, String packageName, String className, String type) {
        switch (type) {
            case "java":
                return new File(modePath,resources.resourcesPathJava+packageName.replace(".",File.pathSeparator)+className+".java").getAbsolutePath();
            case "md":
                return new File(modePath,resources.resourcesPathMd+packageName.replace(".",File.pathSeparator)+className+".md").getAbsolutePath();
            default:
                return  "";
        }
    }

    public String getJavaHome() {
        return javaHome;
    }

    public String getMavenHome() {
        return mavenHome;
    }

    public String getMavenSettingPath() {
        return mavenSettingPath;
    }

    public String getProjectPath() {
        return projectPath;
    }

    public Mode getMainMode() {
        return mainMode;
    }
}
